package com.snake.mylibrary.net;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import okio.Buffer;
import okio.BufferedSink;
import okio.ForwardingSink;
import okio.Okio;
import okio.Sink;

/**
 * 实现上传进度监听
 */

public class CountingRequestBody extends RequestBody {

    protected RequestBody delegate;
    private UploadListener mListener;
    private CountingSink mCountingSink;

    public CountingRequestBody (RequestBody delegate,UploadListener listener){
        this.delegate = delegate;
        mListener = listener;
    }
    protected final class CountingSink extends ForwardingSink{
        private long byteWritten;
        public CountingSink(Sink delegate) {
            super(delegate);
        }

        @Override
        public void write(Buffer source, long byteCount) throws IOException {
            super.write(source, byteCount);
            byteWritten+=byteCount;
            mListener.onRequestProgress(byteWritten,contentLength());
        }
    }
    @Override
    public MediaType contentType() {
        return delegate.contentType();
    }

    @Override
    public long contentLength()  {
        try {
            return delegate.contentLength();
        } catch (IOException e) {
            return -1;
        }
    }

    @Override
    public void writeTo(BufferedSink sink) throws IOException {
        mCountingSink = new CountingSink(sink);
        BufferedSink bufferedSink = Okio.buffer(mCountingSink);
        delegate.writeTo(bufferedSink);
        bufferedSink.flush();
    }
}
